//
//  ZWOAuthViewController.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/19.
//  Copyright © 2016年 flyiron. All rights reserved.
//
/*
App Key：4007028112
App Secret：78e19de439b949bc73f2ac0b3e50eeec
*/
import UIKit
import SVProgressHUD
// APPKEY
let WB_APP_KEY = "4007028112"
// APP_SECRET
let WB_APP_SECRET = "78e19de439b949bc73f2ac0b3e50eeec"
let WB_REDIRECT_URI = "http://www.baidu.com/"

class ZWOAuthViewController: UIViewController {
    override func loadView() {
        view = webView
        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: str)
        let req = NSURLRequest(URL: url!)
        webView .loadRequest(req)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    func setupUI(){
        
       navigationItem.rightBarButtonItem = UIBarButtonItem(title: "快速填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZWOAuthViewController.clickFillBTN))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZWOAuthViewController.clickCancelBTN))
    }
    
    @objc private func clickCancelBTN(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func clickFillBTN(){
        
//        let jsString = "document.getElementById('userId').value='zyy357305734@126.com';document.getElementById('passwd').value='57r7ctz4'"
        let jsString = "document.getElementById('userId').value='13285169282';document.getElementById('passwd').value='panpanpanli'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    lazy var webView:UIWebView = {
        let view = UIWebView()
        view.delegate = self
        return view
    }()

}

extension ZWOAuthViewController:UIWebViewDelegate{
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request)
        guard let url = request.URL else{

            return false
        }
    
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI){
            if let c = url.query where c.containsString("code="){
               let code = c.substringFromIndex("code=".endIndex)
//                print(code)
                
                ZWUserInfoViewModel.sharedViewModel.loadAccessToken(code, finished: { (isSucessd) -> () in
                    if isSucessd{
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            NSNotificationCenter.defaultCenter().postNotificationName("changeRootVC", object: nil)
                            
                        })
                    }else{
                        print("登录失败")
                    }
                    
                })
   
//                GetAccessToken(code)
            }
            return false
        }
        return true
    }
    
//    func GetAccessToken(code:String){
//        let url = "https://api.weibo.com/oauth2/access_token"
//        let parmats = ["client_id":WB_APP_KEY,
//                   "client_secret":WB_APP_SECRET,
//                      "grant_type":"authorization_code",
//                            "code":code,
//                    "redirect_uri":WB_REDIRECT_URI]
//        ZWNetworkTools.sharedTools.request(.Post, urlString: url, parameters: parmats) { (responseObject, error) -> () in
//            if error != nil {
//                 print("网络错误\(error)")
//                return
//            }
//            
////            print("请求成功\(responseObject)")
//            if let dict = responseObject as? [String:AnyObject]{
//                let userModel = ZWUserModel(dict: dict)
////                print(userModel)
//                self.getUserInfo(userModel)
//            }
//            
//        }
//    }
//    
//    func getUserInfo(userModel: ZWUserModel){
//        let urlStr = "https://api.weibo.com/2/users/show.json"
//        let paramets = ["access_token":userModel.access_token ?? "",
//                        "uid":userModel.uid ?? ""]
//        ZWNetworkTools.sharedTools.request(urlString: urlStr, parameters: paramets) { (responseObject, error) -> () in
//            if error != nil {
//                print("网络错误\(error)")
//            }
////            print(responseObject)
//            if let dict = responseObject as? [String: AnyObject]{
//                userModel.name = dict["name"] as? String
//                userModel.avatar_large = dict["avatar_large"] as? String
//                print(userModel)
//            }
//            //保存用户信息
//            self.saveUserInfo(userModel)
//        }
//    }
//   
//    func saveUserInfo(userModel:ZWUserModel){
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.data")
//        print(path)
//        NSKeyedArchiver.archiveRootObject(userModel, toFile: path)
//        
//        //TODO:
//    }
//    
//    //解档
//    func loadUserInfoInSanBox() -> ZWUserModel{
//        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as? NSString)?.stringByAppendingPathComponent("userInfo.data")
//        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path!) as? ZWUserModel
//        return result!
//    }
//    
    
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
